<?php
class ShopController extends Vnf_Controller_Action {
    protected $_dir;

    function addtocartAction() {
        $itemid = $this->_request->getParam("itemid");
        $amount = $this->_request->getParam("amount");
        $att = $this->_request->getParam("att", '');
        $objDAO = new Product();
        
        $newSession = $this->getCart();
        
        if (($itemid > 0) && ($amount > 0)) {
    	    $where = "thistable.ProductNo = $itemid";
            
            if ($att != '') {
                $where .= " AND Attribute1 = '$att'";
            }
    	    
    	    $item = $objDAO->getRecords($where);
            
            //print_r($item);
    	    if (count($item) > 0) {
                $item = $item[0];
                
                $defaultNamespace = new Zend_Session_Namespace('Default');
                $order_id = $defaultNamespace->orderID;
                
                if (!$order_id) {
                    $shopOrder = new ShopOrder();
                    
                    $user_id = null;
                    if ($defaultNamespace->access) {
                        $user = $defaultNamespace->user;
                        $user_id = $user->CustomerNo;
                    }
                    
                    $shopOrder = new ShopOrder();
                    
                    $data = array(
                        'user_id' => $user_id,
                        'date_created' => date('Y-m-d H:i:s', time()),
                        'session_id' => Zend_Session::getId(),
                        'order_status' => 0,
                    );
                    $order_id = $shopOrder->insert($data);
                    
                    $defaultNamespace = new Zend_Session_Namespace('Default');
                    $partnerID = $defaultNamespace->reff;
                    if ($partnerID > 0) {
                        $objPartner = new Partners();
                        $objPartner->increaseValue("AddToCart", 1, "PartnerID = '$partnerID'");
                    }
                }
                
    	        if (!array_key_exists("$itemid-$att", $newSession)) { // chua co item_id
                    //$priceDB = 
                    $new_item = array(
                            'OrderID' => $order_id,
                            'ProductNo' => $itemid,
                            'DiscountYN' => $item->DiscountYN,
                            'Taxable' => $item->Taxable,
                            'CatID' => $item->category_id,
                            'FreeGiftYN' => $item->FreeGiftYN,
                            'Product' => $item->Product,
                            'Attribute' => $att,
                            'Quantity' => $amount,
                            'GiftcardYN' => $item->GiftcardYN,
                            'Price' => $item->AttPrice?$item->AttPrice:($item->PriceRetail>0?$item->PriceRetail:$item->Price),
                        );
                    
                    $order_item = new ShopOrderItem();
                    $order_item->insert($new_item);
    	        } else {
                    // da co item_id trong gio hang
    	            //$newSession["$itemid"]['amount'] += (int)$amount; // count of item - not type of attribute
                    
                    $defaultNamespace = new Zend_Session_Namespace('Default');
                    $order_id = $defaultNamespace->orderID;
                                        
                    $where = "OrderID = '$order_id' AND ProductNo = '$itemid' AND Attribute = '$att'";
                    $order_item = new ShopOrderItem();
                    
                    $fieldName = "Quantity";
                    $order_item->increaseValue($fieldName, $amount, $where);
    	        }
                //$this->saveCart($newSession);
    	        
    	        //print_r($defaultNamespace->cartSession);
                echo Zend_Json::encode(array("msg" => "Item has been added to your cart!<br><a href='" . BASE_URL. "/shop/viewcart'>Click here</a> to view your cart.", "count" => array_sum($newSession)));
    	    }
    	} else {
                echo Zend_Json::encode(array("msg" => "Can't add Item to your cart!<br><a href='" . BASE_URL. "/shop/viewcart'>Click here</a> to view your cart.", "count" => array_sum($newSession)));
        }
        //die;
    }
    
    function addreviewAction() {
    }
    
     function addreviewinnerAction() {
        
       $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
       $this->processLoginAction();
       $defaultNamespace = new Zend_Session_Namespace('Default');
       if (isset($defaultNamespace->access) && ($defaultNamespace->access)) {
            $review = new Review();
            $this->view->member = $meber =$defaultNamespace->user;
            if($this->getParam('submitAddReview', '') != '')
            {
                $arrParam = $this->_request->getParams();
                $customer_id = $meber['CustomerNo'];
                $customer_lastname = $meber['LastName'];
                $customer_firstname = $meber['FirstName'];
                $customer_fullname = $customer_lastname. " ". $customer_firstname;
                $customer_city = $meber['City'];
                $customer_state = $meber['State'];
                //$product_id = $this->_request->getParam("id");
                if($arrParam['score'] != 0)
                {
                    $data = array(
        				'customer_id'=>$customer_id,
        				'product_id'=>$arrParam['id'],
                        'subject' => $arrParam['subject'],
                        'fullname' => $customer_fullname,
                        'city' => $customer_city,
                        'state' => $customer_state,
        				'level'=>$arrParam['score'],
        				'description'=>$arrParam['description'],
        				'datewrite'=> date('Y-m-d H:i:s', time()),
                        'activeYN'=>'0'
        			);
                }
                elseif($arrParam['score'] == 0)
                {
                    $data = array(
        				'customer_id'=>$customer_id,
        				'product_id'=>$arrParam['id'],
                        'subject' => $arrParam['subject'],
                        'fullname' => $customer_fullname,
                        'city' => $customer_city,
                        'state' => $customer_state,
        				'level'=>'5',
        				'description'=>$arrParam['description'],
        				'datewrite'=> date('Y-m-d H:i:s', time()),
                        'activeYN'=>'0'
        			);
                }
            $review->insert($data);
            $id = $arrParam['id'];
            $this->_redirect("shop/reviewlist?id=".$id);
            }
            
        }
    }
    
    function reviewlistAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    function reviewlistinnerAction() {
        
        
		//$this->view->productdetail = $this->_translate->_('productdetail');
		
       
        $objShopProduct = new Product();
		$this->view->productid = $itemid = (int)$this->getParam("id");  
        
        if($itemid > 0) {
            $whereItem = "ProductNo = '" . $itemid . "'";
            $this->view->rsproduct = $rsItem = $objShopProduct->fetchRow($whereItem);
            
            $this->view->cateID = $rsItem->category_id;

             $attr = new Attribute();
            
            $whereItem = "thistable.ProductNo = '" . $itemid . "'";
            $this->view->allAttr = $allAttr = $attr->getRecords($whereItem);
            
            
            $relativeproduct = new RelativeProduct();
            $whereItem = "thistable.ProductNo = '" . $itemid . "'";
            $this->view->relative = $relative = $relativeproduct->getRecords($whereItem);
            
            $productimage = new ProductImage();
            $whereItem = "thistable.ProductNo = '" . $itemid . "'";
            $this->view->imageproduct = $productimage->getRecords($whereItem);
           
           
            //$this->view->reviewid = $reviewid = (int)$this->getParam("reviewid");
            
            $listtreview = new Review();
            
            $whereItem = "thistable.product_id = '" . $itemid . "'". " and thistable.activeYN = '1'";
            //$this->view->listreview = $listreview = $listtreview->getRecords($whereItem, 'review_id DESC');
            //$this->view->countreview = count($listreview);
            
            $this->view->totalRecords = $totalRecords = $listtreview->getTotalRecords($whereItem);
            $this->view->avg = $avg =$listtreview->avg($whereItem);
            $currentPaging = (int) $this->_request->getParam('page', 1);
            $currentPaging--;
            $numberPageView = 5;
            $recordsPerPage = (int) $this->_request->getParam('records', 10);
            $recordsPerPage = $recordsPerPage > 0? $recordsPerPage:10;
            $totalPages = ceil($totalRecords/$recordsPerPage);
            $this->view->pages = $totalPages;

            //echo $currentPage;
            //$link =  BASE_URL . "/index/shop/reviewlist/?cid=$reviewid";
            
            //$tagID = "showbycat";
            $startRecord = $recordsPerPage * $currentPaging;
            //$order = 'CommentID DESC';
            $class = "paging";

            $paging = new Paging();
            $this->view->paging = $paging->getPaging($currentPaging + 1, $totalPages, null, $numberPageView, null, $class,'false');

            $pk = $listtreview->getPrimaryKey();
            
            //$whereItem = "thistable.activeYN = 1";
            $whereItem = "thistable.product_id = '" . $itemid . "'". " and thistable.activeYN = '1'";
            
            $list = $listtreview->getRecords($whereItem, "$pk DESC", $recordsPerPage, $recordsPerPage * $currentPaging);
            $this->view->listreview = $list;
            $this->view->countreview = $totalRecords;
        }
    }
    
    
    function listallreviewAction() {
        //$this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }

    function listallreviewinnerAction() {
            /*$listtreview = new Review();
            //$this->view->listreview = $listreview = $listtreview->getRecords(null, null, '10', '0');
            $this->view->listreview = $totalRecords = $listtreview->getRecords();
            $this->view->countreview = count($totalRecords);*/
            
            $objItem = new Review();
            
            $whereItem = "activeYN = 1";
            $this->view->totalRecords = $totalRecords = $objItem->getTotalRecords($whereItem);
            
            $currentPaging = (int) $this->_request->getParam('page', 1);
            $currentPaging--;
            $numberPageView = 5;
            $recordsPerPage = (int) $this->_request->getParam('records', 10);
            $recordsPerPage = $recordsPerPage > 0? $recordsPerPage:10;
            $totalPages = ceil($totalRecords/$recordsPerPage);
            $this->view->pages = $totalPages;

            //echo $currentPage;
            //$link =  BASE_URL . "/index/shop/list/?cid=$catID&all=$all";
            
            //$tagID = "showbycat";
            $startRecord = $recordsPerPage * $currentPaging;
            //$order = 'CommentID DESC';
            $class = "paging";

            $paging = new Paging();
            $this->view->paging = $paging->getPaging($currentPaging + 1, $totalPages, null, $numberPageView, null, $class,'false');

            $pk = $objItem->getPrimaryKey();
            
            $whereItem = "thistable.activeYN = 1";
            
            $items = $objItem->getRecords($whereItem, "$pk DESC", $recordsPerPage, $recordsPerPage * $currentPaging);
            $this->view->allItems = $items;
            
    }
    
	  public function  testimonialAction() {
	
	}
    
     public function  testimonialinnerAction() {
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
       $this->processLoginAction();
       $defaultNamespace = new Zend_Session_Namespace('Default');
       if (isset($defaultNamespace->access) && ($defaultNamespace->access)) {
            $testimonial = new Testimonial();
            $this->view->member = $meber =$defaultNamespace->user;
            if($this->getParam('submitTestimonial', '') != '') {
            $arrParam = $this->_request->getParams();
                $customer_id = $meber['CustomerNo'];
                $LastName = $meber['LastName'];
                $FirstName = $meber['FirstName'];
                $fullname = $FirstName." ".$LastName;
                $City = $meber['City'];
                $State = $meber['State'];
                //$product_id = $this->_request->getParam("id");
                $data = array(
    				'customerID'=>$customer_id,
    				'fullname'=>$fullname,
    				'city'=>$City,
                    'state'=>$State,
                    'date'=> date('Y-m-d H:i:s', time()),
    				'description'=>$arrParam['description'],
                    'activeYN'=>'0',
    				'Staff'=>$arrParam['Staff'],
                    'image'=>$arrParam['image']
    			);
                
                $fieldUpload = "image";
                $newImageName = '';
                try {
                    $uploadPath = UPLOAD_PATH . "/" . $this->_request->getControllerName();
                    if(Zend_Upload::isFileUpload($fieldUpload)) {
                        if(!is_dir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath))
                        try {
                        mkdir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath, 0777);
                        chmod($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath, 0777);
                        } catch(Exception $ex1){}
                        $newImageName = time(). '_' . rand();
                        $objImageUpload = new Zend_Upload($fieldUpload, $_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $uploadPath);
                        echo "/*" . $objImageUpload->getName() . "*/";
                        $objImageUpload->setName($newImageName);
                        $objImageUpload->upload();
                        $newImageName = $uploadPath . "/" . $newImageName . "." .$objImageUpload->getFileExtention();
                    }
                } catch (Zend_Upload_Exception $ex){ }
                $data[$fieldUpload] = $newImageName;
                
            $testimonial->insert($data);
            //$id = $arrParam['id'];
            $this->_redirect("shop/listtestimonial");
            }
            
        }
        }
     public function  listtestimonialAction() {
	
	}
    
     public function  listtestimonialinnerAction() {
           
       $listtestimonial = new Testimonial();
        $this->view->totalRecords = $totalRecords = $listtestimonial->getTotalRecords();
        $currentPaging = (int) $this->_request->getParam('page', 1);
        $currentPaging--;
        $numberPageView = 5;
        $recordsPerPage = (int) $this->_request->getParam('records', 10);
        $recordsPerPage = $recordsPerPage > 0? $recordsPerPage:10;
        $totalPages = ceil($totalRecords/$recordsPerPage);
        $this->view->pages = $totalPages;
        $startRecord = $recordsPerPage * $currentPaging;
        $class = "paging";

        $paging = new Paging();
        $this->view->paging = $paging->getPaging($currentPaging + 1, $totalPages, null, $numberPageView, null, $class,'false');

        $pk = $listtestimonial->getPrimaryKey();
         $whereItem = "thistable.activeYN = 1";
        //$items = $listtestimonial->getRecords($whereItem, "$pk DESC", $recordsPerPage, $recordsPerPage * $currentPaging);
        
        $this->view->listtestimonial = $listtestimonial->getRecords($whereItem, "$pk DESC", $recordsPerPage, $recordsPerPage * $currentPaging);
	}
	
    function viewprofilecustomerAction() {
        
    }
    function viewprofilecustomerinnerAction() {
        $this->view->customerid = $itemid = (int)$this->getParam("customerid");  
        $this->view->productid = $productid = (int)$this->getParam("product_id");
        
        if($itemid > 0) {
            $customerreview = new Review();
            $whereItem = "thistable.customer_id = '" . $itemid . "'";
            $this->view->profilecustomer = $customerreview->getRecords($whereItem);
        }
    }
    
    function countcartAction() {
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $defaultNamespace = new Zend_Session_Namespace('Default');
        /*
        if (isset($defaultNamespace->cartSession)) {
            $yourCart = $defaultNamespace->cartSession;
        } else {
            $yourCart = array();
        }
        */
        $countItems = $defaultNamespace->countItems > 0?$defaultNamespace->countItems:0;
        echo $countItems; die;
        /*
        $result = array(
            'count' => $countCart,
            'srtCart' => $strCart
        );
        
        echo Zend_Json::encode($result);
        
        die;
        */
    }
    
    function countcart1Action() {
        $yourCart = $this->getCart();
        
        echo array_sum($yourCart);die;
    }
    function viewcartAction() {
    
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
        
        
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        //$this->view->member=$default = new Zend_Session_Namespace('Default');
       
        
        $this->view->yourCart = $yourCart = $this->getCart();
        $this->checkpromotioncode();
        
        //print_r($yourCart);die;
            
        //print_r($yourCart);
        /*
        if (count($yourCart) > 0) {
        
            $itemsId = array_keys($yourCart);
            
            $ids = array();
            foreach($itemsId as $key):
                $id = explode('-', $key);
                $ids[] = $id;
            endforeach;
            
            $objDAO = new Product();
            $where = "ProductNo in (" . implode(',', $ids). ")";
            
            $this->view->yourcart = $objDAO->fetchAll($where);
            
            $this->view->amount = $yourCart;
        }
        */
        $this->view->linkPost = BASE_URL . "/shop/updatecart";
    }
    
    
    
    
	function updatecartAction() {
    
        //print_r($this->getParams());die;
        $yourCart = $this->getCart();
        
        if ($this->_request->isPost()) {
            if (count($yourCart) > 0) {
                $items = $this->_request->getParam("items");
                
                //print_r($items);die;
                $arrItems = explode(",", $items);
                
                
                foreach ($arrItems as $item) {
                    $value = $this->_request->getParam("amount" . $item);
                    
                    $item_att = explode("-", $item);
                    print_r($item_att);
                    $itemID = $item_att[0];
                    $itemAtt = $item_att[1];
                    
                    if (!is_numeric($value)) {
                        $value = 0;
                    }
                    $order_item = new ShopOrderItem();
                    
                    $defaultNamespace = new Zend_Session_Namespace('Default');
                    $order_id = $defaultNamespace->orderID;
                    if ($order_id > 0) {
                        $where = "OrderID = '$order_id' AND ProductNo = '$itemID' AND Attribute = '$itemAtt'";
                        if ($value <= 0) {
                            $order_item->delete($where);
                        } else {
                            $data = array(
                                    'Quantity' => $value
                                );
                                
                            $order_item->update($data, $where);
                        }
                    }
                }
                
                //$this->saveCart($yourCart);
            }
        }
        $this->_redirect("shop/viewcart");
    }
    
    function checkoutAction() {
    	 //lay ra array country			
         /*
        $objCountries = new Countries();
        $this->view->rsCountries = $objCountries->fetchAll();       
        */
	       
        $this->processLoginAction();
        
    	$defaultNamespace = new Zend_Session_Namespace('Default');
        
        $yourCart = $this->getCart();
    	
        if (isset($defaultNamespace->access) && ($defaultNamespace->access)) {
            $this->view->user = $defaultNamespace->user;
        } else {
            $this->view->user = null;
        }
        
        if (count($yourCart) > 0) {
            $itemsId = array_keys($yourCart);
            $itemsId = array_keys($yourCart);
            
            $ids = array();
            foreach($itemsId as $key):
                $id = explode('-', $key);
                $ids[] = $id[0];
            endforeach;
            
            $objDAO = new Product();
            $where = "ProductNo in (" . implode(',', $ids). ")";
            
            $this->view->yourcart = $objDAO->fetchAll($where);
            $this->view->amount = $yourCart;
        }
       	$this->view->linkPost = "{BASE_URL}/shop/updateordercart";
        
        $country = new Country();
        $rowcountry = $country->fetchAll();
        $this->view->rowcountry = $rowcountry;
    }
    
    function orderAction() {
		$this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
        
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
    }
    
    function checkout2Action() {
		$this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
        
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
    }
    
    function checkout2htmlAction() {
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        
        // get all params
        $params = $this->getParams();
        // check this action submit from checkout page
        if($this->_request->isPost()) {
            unset($params['module']);
            unset($params['controller']);
            unset($params['action']);
     
            $memberLogin = $defaultNamespace->user;
            $params['user_id'] = $memberLogin['category_id'];
            //$params['order_time'] = time();
            $params['order_status'] = 0;
            $defaultNamespace->order = $params;
        }
        //print_r($defaultNamespace->order);
    }
    
    function checkout3Action() {
		$this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
        
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
    }
    
    function checkout3htmlAction() {
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $orderAddress = $defaultNamespace->order;
        $orderAddress['order_type'] = $this->getParam('type', 0);
        
        //print_r($orderAddress);
        if (isset($defaultNamespace->cartSession)) {
            $yourCart = $defaultNamespace->cartSession;
        } else {
            $yourCart = array();
        }
              
        if (count($yourCart) > 0) {
        		 $itemsId = array_keys($yourCart);
            
            $objDAO = new Product();
            $where = "ProductNo in (" . implode(',', $itemsId). ")";
            
            $this->view->yourcart = $objDAO->fetchAll($where);
            $this->view->amount = $yourCart;
        }
        //print_r($this->view->yourcart);
        $this->view->linkPost = BASE_URL . "/shop/updatecart";
    }
    
    public function checkoutprocessAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    public function checkoutprocessinnerAction() {
        $this->processLoginAction();
        
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $defaultGiftWrapEnabled = (int)(@$defaultNamespace->giftWrapEnabled);
        $giftWrapEnabled = $this->getParam('giftWrapEnabled', $defaultGiftWrapEnabled);
        $defaultNamespace->giftWrapEnabled = $giftWrapEnabled;
        $sumRealCoupon = 0;
        $sumTax = 0;
        
        $coupon = $defaultNamespace->coupon;
        
        $hasCoupon = false;
        if ($coupon) {
            $hasCoupon = true;
        }
        
        if ($defaultNamespace->access) {
             $params = $this->getParams();
            // check this action submit from checkout page
            if($this->_request->isPost()) {
                unset($params['module']);
                unset($params['controller']);
                unset($params['action']);
         
                //$memberLogin = $defaultNamespace->user;
                //$params['user_id'] = $memberLogin['category_id'];
                //$params['order_time'] = time();
                $params['order_status'] = 0;
                $defaultNamespace->order = $params;
            }
           
            $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
            
            $yourCart = $this->getCart();
                  
            if (count($yourCart) > 0) {
            

                $itemsId = array_keys($yourCart);
            
                $ids = array();
                foreach($itemsId as $key):
                    $id = explode('-', $key);
                    $ids[] = $id[0];
                endforeach;
                
                $objDAO = new Product();
                $where = "ProductNo in (" . implode(',', $ids). ")";
                
                $this->view->yourcart = $yourItems = $objDAO->fetchAll($where);
                $this->view->amount = $amount = $yourCart;
                
                $strMailBody = "";
                
                //$customerInfo = array('Name', 'Address', 'City', 'Phone', 'Mobile', 'Email');

                $strMailBody .= '<table width="100%"><tr valign="top"><td width="50%">';
                $strMailBody .= '<b>' . $this->view->translate->_('Bill to'). ':</b>';
                
                $shipInfo = array();
                // get user loged
                
                $user = $defaultNamespace->user;
                
                //$customerInfo = array('Street', 'City', 'State', 'Zip', 'Country', 'Phone', 'Email', 'FirstName', 'LastName', 'Company');
                $customerInfo = array('Address', 'City', 'State', 'ZipCode', 'Country', 'Phone', 'Email', 'FirstName', 'LastName', 'Company');
                $strShipInfo = "";
                
                $sessionInfo = $defaultNamespace->shipInfo;
                
                foreach($customerInfo as $info):
                    $shipInfo[$info] = (isset($params[$info])?$params[$info]:$sessionInfo[$info]);
                    $strShipInfo .= "<br>" . $this->view->translate->_($info). ': ' . $shipInfo[$info];
                endforeach;
                
                @$strMailBody .= "<br>" . $shipInfo['Company'];
                @$strMailBody .= "<br>" . $shipInfo['FirstName'] . ' ' . $shipInfo['LastName'];
                @$strMailBody .= "<br>" . $shipInfo['Address'];
                @$strMailBody .= "<br>" . $shipInfo['City'] . ', ' . $shipInfo['State'] . ' ' . $shipInfo['ZipCode'] . ' ' ;
                @$strMailBody .= "<br>" . $shipInfo['Country'];
                
                @$strMailBody .= "<br><br>Phone: " . $shipInfo['Phone'];
                @$strMailBody .= "<br>Email: " . $shipInfo['Email'];
                
                
                
                $defaultNamespace->shipInfo = $shipInfo;
                $strMailBody .= '</td><td width="50%">';
                
                $strMailBody .= '<b>' . $this->view->translate->_('Ship to'). ':</b>';
                
                $billInfo = array();
                $strBillInfo = "";
                $shipField = array('Address', 'City', 'State', 'ZipCode', 'Country', 'Phone', 'Email', 'FirstName', 'LastName', 'Company', 'Message');
                
                $sessionBillInfo = $defaultNamespace->billInfo;
                
                foreach($shipField as $info):
                    $billInfo[$info . 'Billing'] = (isset($params[$info . 'Billing'])?$params[$info . 'Billing']:$sessionBillInfo[$info . 'Billing']);
                    //$strMailBody .= '<br>' . $this->view->translate->_($info). ': ' . $billInfo[$info . 'Billing'];
                    $strBillInfo .= '<br>' . $this->view->translate->_($info). ': ' . $billInfo[$info . 'Billing'];
                endforeach;
                
                $defaultNamespace->billInfo = $billInfo;
                $shopOrder = new ShopOrder();
                
                
                @$strMailBody .= "<br>" . $billInfo['Company'. 'Billing'];
                @$strMailBody .= "<br>" . $billInfo['FirstName'. 'Billing'] . ' ' . $billInfo['LastName'. 'Billing'];
                @$strMailBody .= "<br>" . $billInfo['Address'. 'Billing'];
                @$strMailBody .= "<br>" . $billInfo['City'. 'Billing'] . ', ' . $billInfo['State'. 'Billing'] . ' ' . $billInfo['ZipCode'. 'Billing'] . ' ' ;
                @$strMailBody .= "<br>" . $billInfo['Country'. 'Billing'];
                
                @$strMailBody .= "<br><br>Phone: " . $billInfo['Phone'. 'Billing'];
                @$strMailBody .= "<br>Email: " . $billInfo['Email'. 'Billing'];
                @$strMailBody .= "<br>Message: " . $billInfo['Message'. 'Billing'];
                

                
                $shopOrder = new ShopOrder();
                
                $defaultNamespace = new Zend_Session_Namespace('Default');
                $order_id = $defaultNamespace->orderID;
                
                $methodPayment = $defaultNamespace->methodPayment;
                $arayPaymentMethod = array(
                    'cc' => "Credit Card",
                    'gc' => "Gift Card",
                    'pp' => "Paypal",
                );
                
                
                $strMailBody .= '</td></tr></table>';
                $strMailBody .= "<div style='padding:20px 0px;'>
                    <table width='100%' border='1' cellspacing='0' cellpadding='0' style='border:1px solid #D7D7D7'>
                        <tr style='line-height:18px'>
                            <th style='text-align:center'>{$this->view->translate->_('Order Date')}</th>
                            <th style='text-align:center'>{$this->view->translate->_('Status')}</th>
                            <th style='text-align:center'>{$this->view->translate->_('Ship Date')}</th>
                            <th style='text-align:center'>{$this->view->translate->_('Payment By')}</th>
                            <th style='text-align:center'>{$this->view->translate->_('Confirmation No.')}</th>
                            <th style='text-align:center'>{$this->view->translate->_('Shipment Tracking')}</th>
                        </tr>
                        <tr style='line-height:18px'>
                            <td align='center'>" . date('m/d/Y') . "</td>
                            <td align='center'>New</td>
                            <td align='center'></td>
                            <td align='center'>" . @$arayPaymentMethod[$methodPayment] . "</td>
                            <td align='center'></td>
                            <td align='center'></td>
                        </tr>
                    </table>
    </div>";
                
                $strMailBody .= '<div style="padding:5px;background:#D7D7D7;"><b>' . $this->view->translate->_('Items'). ':</b></div>';
                if (count($yourCart) > 0) {
                        $billInfo = $defaultNamespace->billInfo;
                        $billingState = '';
                        $hasTax = false;
                        @$billingState = strtolower($billInfo['StateBilling']);
                        if ($billingState == 'ca' || $billingState == 'cali' || $billingState == 'california') {
                            $hasTax = true;
                        } else {
                        }
                
                    $strMailBody .= "
                    <table width='100%' border='0' cellspacing='0' cellpadding='0'>
                        <tr style='line-height:18px'>
                            <th>{$this->view->translate->_('Quantity')}</th>
                            <th>{$this->view->translate->_('SKU')}</th>
                            <th>{$this->view->translate->_('Title')}</th>
                            <th>{$this->view->translate->_('Price')}</th>
                            <th>{$this->view->translate->_('Coupon')}</th>
                            <th>{$this->view->translate->_('Tax')}</th>
                            <th style='text-align:right'>{$this->view->translate->_('Total')}</th>
                        </tr>
    ";
                    $sum = 0;
                    $stt = 1;
                    foreach($yourCart as $item):
                        $price = $item->Price;                         
                        $attKey = $item->Attribute;
                        
                            $title = $item->Product;
                            $price = $item->Price;
                            //$price = $att['price']; 



                            //$price = $item->Price;
                            $quantity = $item->Quantity;
                            $subTotal = $price * $quantity;
                            
                            $strMailBody .= 
        "
                            <tr style='line-height:20px'>
                                <td>" . $quantity . "</td>
                                <td></td>
                                <td>{$title}" . (($attKey)?"<br>$attKey":"") ."</td>
                                <td>\${$price}</td>
                                <td>";
                            if ($hasCoupon && $item->DiscountYN != 'No') {
                                $realCoupon = 0;
                                if (@$coupon['CouponType'] && @$coupon['Value']) {
                                    $couponType = $coupon['CouponType'];
                                    $couponCode = $coupon['CouponCode'];
                                    $couponValue = $coupon['Value'];
                                    
                                    $couponCatID = $coupon['CatID'];
                                    
                                    $allCategory = $this->view->allCategory;
                                    $children = array();
                                    @$children = $allCategory[$couponCatID]['children'];
                                    $children[] = $couponCatID;
                                    
                                    if ($couponCatID == null || in_array($item->CatID, $children)) {
                                    
                                        if ($couponType == '%') {
                                            $realCoupon = round($subTotal * ($couponValue)/100, 2);
                                        } elseif($couponType == '$') {
                                            //$realCoupon = $couponValue;
                                        }
                                        $subTotal -= $realCoupon;
                                    }
                                }
                                $sumRealCoupon += $realCoupon;
                                
                                $strMailBody .= "-\${$realCoupon}";
                            }
                            $strMailBody .= "</td><td>";
                            if ($hasTax && $item->Taxable == 'Yes') {
                                $tax = round($subTotal * 8.75/100, 2);
                                $sumTax += $tax;
                                $subTotal += $tax;
                                
                                $strMailBody .= "\${$tax}";
                            }
                            $strMailBody .= "</td>
                                <td style='text-align:right'>\${$subTotal}</td>
                            </tr>
        ";
                            $sum += $subTotal;
                    endforeach;
                    
                    $strMailBody .= '                </table>';
                    $strMailBody .= "<div style='text-align:right;padding:5px 0px;'>" . $this->view->translate->_('Sub-Total') . ': $' . $sum . "</div>";
                    $this->view->total = $sum;
                    
                    
                    // more email
                    
                    //$coupon = $defaultNamespace->coupon;
                    
                    $strMailBody .= '<div class="pink" style="text-align:right;font-size:16px">';
                    if ($coupon) {
                        $strMailBody .= $coupon['CouponTitle'];
                    }
                    $strMailBody .= '</div>
        <div style="text-align:right;padding:10px 0px;line-height:20px">
            <table align="right">
                <tr>
                    <td>
                        Sales Tax
                    </td>
                    <td width="100" align="right">';

                                        
                    $sumWithCoupon = $sum;
                    
                    
                    $strMailBody .= '</td>
                </tr>
                <tr>
                    <td>
                        Total
                    </td>
                    <td width="100" align="right">
                        $' . $sumWithCoupon . '
                    </td>
                </tr>';
                
                if ($coupon) {
                
                    $couponCode = "";
                    
                    
                    $realCoupon = $defaultNamespace->realCoupon>0?$defaultNamespace->realCoupon:0;
                    
                    
                    if (@$coupon['CouponType'] && @$coupon['Value']) {
                        $couponType = $coupon['CouponType'];
                        $couponCode = $coupon['CouponCode'];
                        $couponValue = $coupon['Value'];
                        $realCoupon = 0;
                        if ($couponType == '%') {
                            //$realCoupon = round($sumWithCoupon * ($couponValue)/100, 2);
                        } elseif($couponType == '$') {
                            $realCoupon = $couponValue;
                            $sumWithCoupon -= $realCoupon;
                            $strMailBody .= '<tr>
                                <td>
                                    Coupon: <?php echo $couponCode;?>
                                </td>
                                <td width="100" align="right">
                                    -$' .  $realCoupon . '
                                </td>
                            </tr>';
                        }
                    }
                }
                $strMailBody .= '<tr>
                    <td>
                        Add Signature Confirmation
                    </td>
                    <td width="100" align="right">';
                        if($defaultNamespace->SignatureConfirmation == 1) {
                            $strMailBody .= "$2";
                            $sumWithCoupon += 2;
                        } else {
                            $strMailBody .= "$0";
                        }
                    $strMailBody .= '</td>
                </tr>
                <tr>
                    <td>
                        Shipping
                    </td>
                    <td width="100" align="right">$' . $defaultNamespace->shipping;
                    
                    $sumWithCoupon += $defaultNamespace->shipping;
                $strMailBody .= '</td>
                </tr>';
                
                $StoreCredit = 0;
                // get Store Credit from DB
                $user = $defaultNamespace->user;
                @$StoreCredit = $user->StoreCredit;
                
                $StoreCredit = $StoreCredit>=$sumWithCoupon?$sumWithCoupon:$StoreCredit;
                
                if($StoreCredit > 0) {
                    $defaultNamespace->StoreCredit = $StoreCredit;
                    
                    $sumWithCoupon -= $StoreCredit;
                
                    $strMailBody .= '<tr>
                        <td>
                            Store Credit
                        </td>
                        <td width="100" align="right">
                            -$' . $StoreCredit . '
                        </td>
                    </tr>';
                }
                $giftCard = $defaultNamespace->giftCard;
                $giftCardPrice = $defaultNamespace->giftCardPrice;
                
                
                $giftCardPrice = $giftCardPrice>=$sumWithCoupon?$sumWithCoupon:$giftCardPrice;
                if($giftCardPrice > 0) {
                    $sumWithCoupon -= $giftCardPrice;

                    $strMailBody .= '<tr>
                        <td>
                            Gift card
                        </td>
                        <td width="100" align="right">
                            -$' . $giftCardPrice;
                    $strMailBody .= '
                        </td>
                    </tr>';
                }
                    $strMailBody .= '<tr>
                    <td>
                        <b>TOTAL DUE</b>
                    </td>
                    <td width="100" align="right">
                        $' .$sumWithCoupon . '
                    </td>
                </tr>
            </table>
        </div>
        <div style="clear:both;"></div>';
        
        $emailContent = $strMailBody;
        
                /*$billinginfo = array(
                    'BillToAddress' =>$billInfo['AddressBilling'],
                    'BillToCity' => $billInfo['CityBilling'],
                    'BillToState' => $billInfo['StateBilling'],
                    'BillToZipCode' => $billInfo['ZipCodeBilling'],
                    'BillToCountry' => $billInfo['CountryBilling'],
                    'BillToPhone' => $billInfo['PhoneBilling'],
                    'BillToName' => $billInfo['NameBilling'],
                    'BillToCompany' => $billInfo['CompanyBilling'],
                    'BillToMessage' => $billInfo['MessageBilling'],
                );
                
                $shippinginfo = array(
                    'ShipToAddress' =>$shipInfo['Address'],
                    'ShipToCity' => $shipInfo['City'],
                    'ShipToState' => $shipInfo['State'],
                    'ShipToZipCode' => $shipInfo['ZipCode'],
                    'ShipToCountry' => $shipInfo['Country'],
                    'ShipToPhone' => $shipInfo['Phone'],
                    'ShipToEmail' => $shipInfo['Email'],
                    'ShipToFirstName' => $shipInfo['FirstName'],
                    'ShipToLastName' => $shipInfo['LastName'],
                    'ShipToCompany' => $shipInfo['Company']
                );*/
        $dataUpdate = array(
                'ship_info' => $strShipInfo,
                'bill_info' => $strBillInfo,
                'email_content' => $emailContent,
                'total' => $sumWithCoupon,
                'description' => Zend_Json::encode(array('billInfo' => $billInfo, 'shipInfo' => $shipInfo)),
                    'BillToAddress' =>$billInfo['AddressBilling'],
                    'BillToCity' => $billInfo['CityBilling'],
                    'BillToState' => $billInfo['StateBilling'],
                    'BillToZipCode' => $billInfo['ZipCodeBilling'],
                    'BillToCountry' => $billInfo['CountryBilling'],
                    'BillToPhone' => $billInfo['PhoneBilling'],
                    'BillToFirstName' => @$billInfo['FirstNameBilling'],
                    'BillToLastName' => @$billInfo['LastNameBilling'],
                    'BillToCompany' => $billInfo['CompanyBilling'],
                    'BillToMessage' => $billInfo['MessageBilling'],
                    'ShipToAddress' =>$shipInfo['Address'],
                    'ShipToCity' => $shipInfo['City'],
                    'ShipToState' => $shipInfo['State'],
                    'ShipToZipCode' => $shipInfo['ZipCode'],
                    'ShipToCountry' => $shipInfo['Country'],
                    'ShipToPhone' => $shipInfo['Phone'],
                    'ShipToEmail' => $shipInfo['Email'],
                    'ShipToFirstName' => $shipInfo['FirstName'],
                    'ShipToLastName' => $shipInfo['LastName'],
                    'ShipToCompany' => $shipInfo['Company'],
                    'ShippingType' => $defaultNamespace->shippingType,
                    
                    'Add_Signature' => @$defaultNamespace->SignatureConfirmation,
                    'PaymentMethod' => @$defaultNamespace->methodPayment,
                    'GiftWrapYN' => @$defaultNamespace->giftWrapEnabled,
                    'ShippingCost' => @$defaultNamespace->shipping,
                    'GiftCardNumber' => @$defaultNamespace->giftCard,
                    'GiftCardAmount' => $giftCardPrice,
                    'StoreCreditAmount' => $StoreCredit,
                    'Tax' => $sumTax,
                    'coupon_value' => $sumRealCoupon,
                    'PrintYN' => 'N',
                    'DownloadYN' => 'N',
                    'ConfirmationNo' => time(),
                    'Message' => $billInfo['Message'. 'Billing'],

                    'ShipToCompany' => $shipInfo['Company'],
                    
            );
        $where = "order_id = '$order_id'";
        $shopOrder->update($dataUpdate, $where);
        
        
        $defaultNamespace->sumWithCoupon = $sumWithCoupon;
                    
                    
                    $this->view->mailBody = $strMailBody;
                    
                    $defaultNamespace->mailBody = $strMailBody;
                    $defaultNamespace->cartTotal = $sum;
                    
                    //$emailFrom = $params['EmailBilling'];
                    
                    $strMailBody = "Thanks for your order, " . $shipInfo['FirstName'] . ' ' . $shipInfo['LastName'] . "!<br><br>If you need to check the status of your order please visit our home page at skinspastore.com and click on <a href='" . BASE_URL . "/index/index/preparelogin'>sign in</a> at the top of any page.<br><br>" . $strMailBody;
                    
                    $emailFrom = $user['Email'];
                    
                    $conf = Vnf::getConfigs('conf');
                    
                    $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
                    @$emailshop = $conf->emailshop?$conf->emailshop:'info@'.$domain;
                    
                    
                    /*
                    // this code will use in next step
                    if ($_SERVER['HTTP_HOST'] != 'localhost') {
                        $mail = new Zend_Mail("utf-8");
                        $mail->setBodyHtml($strMailBody)
                            ->setFrom($emailFrom)
                            ->addTo($emailshop)
                            ->addBcc('ptp285@gmail.com')
                            ->addCc($emailFrom)
                            ->setSubject($this->view->translate->_('Order Information'))
                            ->send();
                    }
                    */
                }
            }
        } // login
        //$defaultNamespace->cartSession = null;
        //$defaultNamespace->order = null;
   }
    public function checkoutprocess2Action() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        
         $params = $this->getParams();
        // check this action submit from checkout page
        if($this->_request->isPost()) {
            unset($params['module']);
            unset($params['controller']);
            unset($params['action']);
     
            //$memberLogin = $defaultNamespace->user;
            //$params['user_id'] = $memberLogin['category_id'];
            //$params['order_time'] = time();
            $params['order_status'] = 0;
            $defaultNamespace->order = $params;
        }
       
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        
        $yourCart = $this->getCart();
              
        if (count($yourCart) > 0) {
        
            $itemsId = array_keys($yourCart);
            
            $objDAO = new Product();
            $where = "ProductNo in (" . implode(',', $itemsId). ")";
            
            $this->view->yourcart = $yourItems = $objDAO->fetchAll($where);
            $this->view->amount = $amount = $yourCart;
            
            $strMailBody = "";
            
            //$customerInfo = array('Name', 'Address', 'City', 'Phone', 'Mobile', 'Email');
            $customerInfo = array('Address', 'City', 'State', 'ZipCode', 'Country', 'Phone', 'Mobile', 'Email', 'Name', 'Company', 'Message');

            $strMailBody .= '<b>' . $this->view->translate->_('Customer info'). ':</b>';
            
            foreach($customerInfo as $info):
                //$strMailBody .= '<br>' . $this->view->translate->_($info). ': ' . $params[$info];
            endforeach;
            
            $strMailBody .= '<br><b>' . $this->view->translate->_('Billing info'). ':</b>';
            
            foreach($customerInfo as $info):
                $strMailBody .= '<br>' . $this->view->translate->_($info). ': ' . $params[$info . 'Billing'];
            endforeach;
            
            $strMailBody .= '<br><b>' . $this->view->translate->_('Order info'). ':</b>';
            if (count($yourItems) > 0) {
                $strMailBody .= "
                <table width='100%' border='0' cellspacing='0' cellpadding='0'>
                    <tr>
                        <td>{$this->view->translate->_('Order')}</td>
                        <td>{$this->view->translate->_('Title')}</td>
                        <td>{$this->view->translate->_('Price')}</td>
                        <td>{$this->view->translate->_('Quantity')}</td>
                        <th>{$this->view->translate->_('Sub Total')}</th>
                    </tr>
";
                $sum = 0;
                $stt = 1;
                foreach($yourItems as $item):
                    $title = $item->Product;
                    $price = $item->Price;
                    $quantity = $amount['' . $item->ProductNo];
                    $subTotal = $price * $quantity;
                    $sum += $price * $amount['' . $item->ProductNo];
                    
                    $strMailBody .= 
"
                    <tr>
                        <td>" . $stt++ . "</td>
                        <td>{$title}</td>
                        <td>{$price}</td>
                        <td>{$quantity}</td>
                        <td>{$subTotal}</td>
                    </tr>
";
                endforeach;
                
                $strMailBody .= '                </table>';
                $strMailBody .= $this->view->translate->_('Total') . ': ' . $sum;
                
                $emailFrom = $params['Email'];
                
                $conf = Vnf::getConfigs('conf');
                
                $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
                @$emailshop = $conf->emailshop?$conf->emailshop:'info@'.$domain;
                
                $this->view->mailBody = $strMailBody;
                
                if ($_SERVER['HTTP_HOST'] != 'localhost') {
                    $mail = new Zend_Mail("utf-8");
                    $mail->setBodyHtml($strMailBody)
                        ->setFrom($emailFrom)
                        ->addTo($emailshop)
                        ->addBcc('ptp285@gmail.com')
                        ->addCc($emailFrom)
                        ->setSubject($this->view->translate->_('Order Information'))
                        ->send();
                }
            }
        }
        
        $this->emptyCart();
        //$defaultNamespace->cartSession = null;
        //$defaultNamespace->order = null;
   }
    function viewcartajaxAction() {
        //$this->setLayout(DEFAULT_LAYOUT);
        //$this->prepareData();
        
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        
        $yourCart = $this->getCart();
        
        
        $strCart = "";
        $countCart = 0;
        if (count($yourCart) > 0) {
            $countCart = array_sum($yourCart);
            
            $itemsId = array_keys($yourCart);
            
            $objDAO = new Product();
            $where = "ProductNo in (" . implode(',', $itemsId). ")";
            
            $this->view->yourcart = $cartItems = $objDAO->fetchAll($where);
            $this->view->amount = $amount = $yourCart;
            
            $strCart = '<table width="100%" border="0" cellspacing="0" cellpadding="5" class="carttable">';
            
            $strItem = "";
            $i = 0;
            $sum = 0;
            
            //print_r($cartItems);die;
            
            foreach ($cartItems as $item):
                $price = $item->Price; 
                $strItem .= ($i++ >0 ? ",":"") . $item->ProductNo;
                
                $sum += $price * $amount['' . $item->ProductNo];
                
                $strCart .= '<tr' . (($i%2==0)?' class="odd"':'') .'>
                        <td style="text-align:left">
                            ' . $item->Description . '
                        </td>
                        <td>
                            ' . $this->view->formText('amount' . $item->ProductNo, $amount['' . $item->ProductNo], array('style' => 'width:20px;', 'maxlength' => '3', 'onchange' => "javascript:checkNumber(this);", 'onkeyup' => "javascript:checkNumber(this);")) . '
                        </td>
                        <td style="text-align:right;">
                            ' .  $price * $amount['' . $item->ProductNo] . '
                        </td>
                    </tr>'
                ;

            endforeach;
            $strCart .= '
                            <tr>
                                <td colspan="3" style="text-align:right;padding-right:10px">
                                    <b>' . $this->view->translate->_('Total') . ':</b> ' . $sum . '
                                <td>
                            </tr>
                        </table>';
            
            //echo $strCart;
            
        }
        //print_r($this->view->yourcart);
        $this->view->linkPost = BASE_URL . "/shop/updatecart";
        
        $result = array(
            'count' => $countCart,
            'srtCart' => $strCart
        );
        
        echo Zend_Json::encode($result);
        
        die;
    }
    
    public function listAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    public function listinnerAction() {
        $this->view->catID = $catID = $this->_request->getParam('cid', 0);
        $all = $this->_request->getParam('all', 0);
        
        
        
        $where = "category_id in  ($catID)";
        
        //$objCategory = new Category();
        //$allCategory = $objCategory->getCacheOfCategory();
        
        //$this->view->thisCat = $allCategory[$catID];
        //$objCategory->fetchRow($where);
        // get child page
        if ($all == 1) {
            $allCategory = $this->view->allCategory;
            $currentCat = @$allCategory[$catID];
            
            $pageWithSubPage = $currentCat['children'];
            // join current page
            //$pageWithSubPage[] = $currentPage;//['category_id'];
            $pageWithSubPage[] = $catID;//['category_id'];
            // parse to string
            $strPageWithSubPage = implode(',', $pageWithSubPage);
            
            $where = "category_id in  ($strPageWithSubPage)";
        }
        
        $objItem = new Product();
        
        $this->view->totalRecords = $totalRecords = $objItem->getTotalRecords("$where");

            $currentPaging = (int) $this->_request->getParam('page', 1);
            $currentPaging--;
            $numberPageView = 5;
            $recordsPerPage = (int) $this->_request->getParam('records', 12);
            $recordsPerPage = $recordsPerPage > 0? $recordsPerPage:12;
            $totalPages = ceil($totalRecords/$recordsPerPage);
            $this->view->pages = $totalPages;

            //echo $currentPage;
            $link =  BASE_URL . "/index/shop/list/?cid=$catID&all=$all";
            
            $tagID = "showbycat";
            $startRecord = $recordsPerPage * $currentPaging;
            //$order = 'CommentID DESC';
            $class = "paging";

            $paging = new Paging();
            $this->view->paging = $paging->getPaging($currentPaging + 1, $totalPages, $link, $numberPageView, $tagID, $class,'false');

            $pk = $objItem->getPrimaryKey();
            $items = $objItem->getRecords($where, "$pk DESC", $recordsPerPage, $recordsPerPage * $currentPaging);


            $this->view->allItems = $items;
            
    }
    
	function detailAction() {
    }
	function detailinnerAction() {
		$this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
        
		//$this->view->productdetail = $this->_translate->_('productdetail');
		
       
        $objShopItem = new Product();
		$this->view->itemid = $itemid = (int)$this->getParam("id");    
        
        if($itemid > 0) {
            $whereItem = "ProductNo = '" . $itemid . "'";
            $this->view->rsItem = $rsItem = $objShopItem->fetchRow($whereItem);
            
            $this->view->catID = $rsItem->category_id;

            $attr = new Attribute();
            
            $whereItem = "thistable.ProductNo = '" . $itemid . "'";
            $this->view->allAttr = $allAttr = $attr->getRecords($whereItem);
            
            
            $relativeproduct = new RelativeProduct();
            $whereItem = "thistable.ProductNo = '" . $itemid . "'";
            $this->view->relative = $relative = $relativeproduct->getRecords($whereItem);
            
             $productimage = new ProductImage();
            $whereItem = "thistable.ProductNo = '" . $itemid . "'";
            $this->view->imageproduct = $productimage->getRecords($whereItem, null, '4', '0');
            
            $review = new Review();
            $whereItem = "thistable.product_id = '" . $itemid . "'";
            //$this->view->review = $review->getRecords($whereItem, '', '1', '0');
            
             $review = new Review();
            $whereItem = "thistable.product_id = '" . $itemid . "'". " and thistable.activeYN = '1'";
            //$this->view->review = $review =$review->getRecords($whereItem, '', '1', '0');
            $this->view->avg = $avg =$review->avg($whereItem);
            
             $listtreview = new Review();
            $whereItem = "thistable.product_id = '" . $itemid . "'". " and thistable.activeYN = '1'";
            //echo ($whereItem);
            $this->view->listreview = $listreview = $listtreview->getRecords($whereItem, 'review_id DESC');
            $this->view->countreview = count($listreview);
            //echo "Count Attrs" . count($allAttr);
        }
    }
    
    public function emptycartAction() {
        //$defaultNamespace = new Zend_Session_Namespace('Default');
        //$defaultNamespace->cartSession = array();
        $this->emptyCart();
        
        $this->_redirect('/');
    }
    
    public function searchAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function searchinnerAction() {
        $this->view->key = $key = $this->_request->getParam('key', '');
        
        $db = Zend_Registry::get('db');
        
        $tmpKey = $db->quote($key);
        $tmp2Key = $db->quote("%$key%");
        
        //$where = "thistable.ProductNo =  $tmpKey OR thistable.Product like $tmp2Key";
        $where = "thistable.ProductNo =  $tmpKey OR thistable.SKU =  $tmpKey OR thistable.Product like $tmp2Key";
        
        
        $objItem = new Product();
        
        $this->view->totalRecords = $totalRecords = $objItem->getTotalRecords("$where");
        

            $currentPaging = (int) $this->_request->getParam('page', 1);
            $currentPaging--;
            $numberPageView = 5;
            $recordsPerPage = (int) $this->_request->getParam('records', 12);
            $recordsPerPage = $recordsPerPage > 0? $recordsPerPage:12;
            $totalPages = ceil($totalRecords/$recordsPerPage);
            $this->view->pages = $totalPages;

            //echo $currentPage;
            $link =  BASE_URL . "/index/shop/search/?key=" . urlencode($key);
            
            $tagID = "showbycat";
            $startRecord = $recordsPerPage * $currentPaging;
            //$order = 'CommentID DESC';
            $class = "paging";

            $paging = new Paging();
            $this->view->paging = $paging->getPaging($currentPaging + 1, $totalPages, $link, $numberPageView, $tagID, $class,'false');

            $pk = $objItem->getPrimaryKey();
            $items = $objItem->getRecords($where, "$pk DESC", $recordsPerPage, $recordsPerPage * $currentPaging);


            $this->view->allItems = $items;
            
    }
    
    public function checkuserAction() {
        $defaultNamespace = new Zend_Session_Namespace('Default');
        //$defaultNamespace = new Zend_Session_Namespace('Default');
        
        $method = $this->getParam('m', null);
        
        if ($method) {
            $defaultNamespace->methodPayment = $method;
        }

        if (!$defaultNamespace->access) {
            $this->setLayout(DEFAULT_LAYOUT);
            $this->prepareData();
        } else {
            $this->_redirect("shop/order");
        }
    }
    
    public function checkuserinnerAction() {
        $this->view->paramsEncode = '{"controller":"shop","action":"order","module":"index"}';
        
    }
    
    public function usestoreAction() {
        $defaultNamespace = new Zend_Session_Namespace('Default');
        //$defaultNamespace = new Zend_Session_Namespace('Default');
        

        if (!$defaultNamespace->access) {
            $this->setLayout(DEFAULT_LAYOUT);
            $this->prepareData();
        } else {
            $this->_redirect("shop/viewcart");
        }
    }
    
    public function usestoreinnerAction() {
        $this->view->paramsEncode = '{"controller":"shop","action":"viewcart","module":"index"}';
        //$this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        //$this->processLoginAction();
        
    }
    
    
    public function usestoreprocessAction() {
        //$defaultNamespace = new Zend_Session_Namespace('Default');
        
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();

    }
    
    public function usestoreprocessinnerAction() {
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        
        if (!$defaultNamespace->access) {
        } else {
            $this->_redirect("shop/viewcart");
        }
        
    }
    
     public function customerprocessAction() {
        //$defaultNamespace = new Zend_Session_Namespace('Default');
        
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function customerprocessinnerAction() {
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $defaultNamespace = new Zend_Session_Namespace('Default');
         $orderbyphone = $defaultNamespace->orderbyphone;
        $defaultNamespace->user = null;
        $defaultNamespace->access = false;
        $id = $this->_request->getParam('id', 0);
        $userOb = new Customer();
        $where = "thistable.CustomerNo='$id'";
        $result = $userOb->getRecords($where);
        if (count($result) > 0)
        {
            $defaultNamespace->user = $result[0];
            $defaultNamespace->access = true;
            $this->_redirect("shop/viewcart");
        }
    }
    
    public function cccheckoutAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function cccheckoutinnerAction() {
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        if ($defaultNamespace->access) {
        }
    }
    
    public function processpaymentAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function processpaymentinnerAction() {
        $this->processLoginAction();
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $defaultNamespace = new Zend_Session_Namespace('Default');
        if ($defaultNamespace->access) {
            $user = $defaultNamespace->user;
            $user_id = $user->CustomerNo;
            
            $shopOrder = new ShopOrder();
            
            $yourCart = $this->getCart();
            
            /*
            $description = array(
                'cart' => $yourCart,
                'shipInfo' => $defaultNamespace->shipInfo,
                'billInfo' => $defaultNamespace->billInfo,
                'total' => $defaultNamespace->cartTotal,
            );
            $data = array(
                'user_id' => $user_id,
                'description' => Zend_Json::encode($description),
                'date_created' => date('Y-m-d H:i:s', time()),
                'order_status' => 0,
            );
            */
            
            //$shopOrder->insert($data);
            
            $defaultNamespace = new Zend_Session_Namespace('Default');
            $order_id = $defaultNamespace->orderID;
            
            $where = "order_id = '$order_id'";
            
            $shopOrder->update(
                array(
                    'order_status' => 1,
                    'MasterCard' => $this->getParam('cc', ''),
                    'PaymentBy' => $this->getParam('card_type', ''),
                    'ShipNo' => $this->getParam('ShipNo', ''),
                    'CVV' => $this->getParam('CVV', ''),
                    'ExpirationDate' => $this->getParam('yearexp', '') . '-' . $this->getParam('monthexp', ''),
                )
                , $where
            );
            
            
            $strMailBody = $defaultNamespace->mailBody;
                        
            $conf = Vnf::getConfigs('conf');
            
            $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
            @$emailshop = $conf->emailshop?$conf->emailshop:'info@'.$domain;
            
            // this code will use in next step
            if ($_SERVER['HTTP_HOST'] != 'localhost') {
                $mail = new Zend_Mail("utf-8");
                $mail->setBodyHtml($strMailBody)
                    ->setFrom($emailshop)
                    ->addTo($emailshop)
                    ->addBcc('ptp285@gmail.com')
                    ->addCc($user['Email'])
                    ->setSubject($this->view->translate->_('Order Information'))
                    ->send();
            }
            //$this->emptyCart();
            /*
            $defaultNamespace->cartSession = null;
            $defaultNamespace->shipInfo = null;
            $defaultNamespace->billInfo = null;
            $defaultNamespace->cartTotal = null;
            */
                    
            $defaultNamespace = new Zend_Session_Namespace('Default');
            $partnerID = $defaultNamespace->reff;
            if ($partnerID > 0) {
                
                $objPartner = new Partners();
                
                $objPartner->increaseValue("Ordered", 1, "PartnerID = '$partnerID'");
            }
            
            $defaultNamespace->coupon = null;
            $defaultNamespace->methodPayment = null;

            $giftcard = new Giftcard();
            
            $giftcard->increaseValue("Amount", -1 * $defaultNamespace->giftCardPrice, "GiftCardNo = '" . $defaultNamespace->giftCard . "'", "BuyerID = '" . $user_id . "'");
            
            $customer = new Customer();
            $customer->increaseValue("StoreCredit", -1 * $defaultNamespace->StoreCredit, "CustomerNo = '" . $user_id . "'");
            
            $updateCustomer = $customer->getRecords("CustomerNo = '" . $user_id . "'");
            
            if (count($updateCustomer) > 0) {
                $defaultNamespace->user = $updateCustomer[0];
            }
            
            $defaultNamespace->coupon = null;
            $defaultNamespace->methodPayment = null;
            $defaultNamespace->cartSession = null;
            $defaultNamespace->shipInfo = null;
            $defaultNamespace->billInfo = null;
            $defaultNamespace->cartTotal = null;
            $defaultNamespace->giftCard = null;
            $defaultNamespace->giftCardPrice = null;
            $defaultNamespace->StoreCredit = null;
            $defaultNamespace->SignatureConfirmation = null;
            $defaultNamespace->countItems = 0;
            $defaultNamespace->shipping = null;
            
            
            Zend_Session::regenerateId();
       }
    }
    
    public function getCart() {
        $defaultNamespace = new Zend_Session_Namespace('Default');
        
        $newSession = array();
        
        $sesion_id = Zend_Session::getId();
        $shopOrder = new ShopOrder();
        $cartDB = $shopOrder->fetchRow("session_id = '$sesion_id'");
        /*echo "<pre>";
        print_r($cartDB);
        echo "</pre>";*/
        $order_id = null;
        
        $defaultNamespace->orderID = null;
        $defaultNamespace->countItems = 0;
        
        if (count($cartDB) > 0) {
            $order_id = $cartDB->order_id; // get order_id;
            // get all items in order
            $order_item = new ShopOrderItem();
            $where = "order_id = '$order_id'";
            $allProducts = $order_item->getRecords("$where");
          
            $data = array();
            
            $defaultNamespace->cartTotal = 0;
            if (count($allProducts) > 0) {
            
                // has item in order
                foreach($allProducts as $item):
                    $data[$item->ProductNo . '-' . $item->Attribute ] = $item;
                    $defaultNamespace->countItems += $item->Quantity;
                    $defaultNamespace->cartTotal += $item->Quantity * $item->Price;
                endforeach;
            }
            //$defaultNamespace->cartSession = $data;
            $newSession = $data;
            $defaultNamespace->orderID = $order_id;
            
            if($defaultNamespace->access) {
                $user = $defaultNamespace->user;
                
                //print_r($user);
                
                if($user) {
                    $where = "order_id = '$order_id'";
                    $user_id = $user->CustomerNo;
                    $orderbyphone = $defaultNamespace->orderbyphone;
                    $shopOrder = new ShopOrder();
                    $shopOrder->update(
                        array(
                            'user_id' => $user_id,
                            'orderbyphone' => $orderbyphone
                        )
                    , $where);
                }
            }
        }
        
        //print_r($data);die;
        //$columns = array('session_id', 'user_id', 'date_updated');
        //$shopOrder->saveRow()
        
        return $newSession;
        
    }
    
    public function saveCart($newSession) {
        $defaultNamespace = new Zend_Session_Namespace('Default');
        
        $defaultNamespace->cartSession = $newSession;
        
        
        $sesion_id = Zend_Session::getId();
        
        $shopOrder = new ShopOrder();
        $cartDB = $shopOrder->fetchRow("session_id = '$sesion_id'");
        
        if (count($cartDB) > 0) {
            // get old order
            $oder_id = $cartDB->order_id; // get order_id;
            
        } else {
            // create new order
            $data = array(
                'sesion_id' => $sesion_id,
                'date_created' => date('Y-m-d H:i:s', time()),
            );
            if ($defaultNamespace->access) {
                $user = $defaultNamespace->user;
                $user_id = $defaultNamespace->CustomerNo;
                $data['user_id'] = $user_id;
            }
            
            $oder_id = $shopOrder->insert($data);
        }
    }
    
    public function emptyCart() {
    
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $order_id = $defaultNamespace->orderID;
        
        if ($order_id > 0) {
            $shopOrder = new ShopOrder();
            $shopOrder->delete("order_id = '$order_id'");
            
            $order_item = new ShopOrderItem();
            $order_item->delete("OrderID = '$order_id'");
        }
        
        $defaultNamespace->coupon = null;
        $defaultNamespace->methodPayment = null;
        $defaultNamespace->cartSession = null;
        $defaultNamespace->shipInfo = null;
        $defaultNamespace->billInfo = null;
        $defaultNamespace->cartTotal = null;
        $defaultNamespace->giftCard = null;
        $defaultNamespace->giftCardPrice = null;
        $defaultNamespace->StoreCredit = null;
        $defaultNamespace->SignatureConfirmation = null;
        $defaultNamespace->countItems = 0;
    }
    public function promotioncodeAction() {
        $promotionCode = $this->getParam('PromotionCode', '');
        
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $defaultNamespace->coupon = null;
        
        if($promotionCode) {
            $objCoupon = new Coupon();
            
            $db = Zend_Registry::get('db');
            $coupon = $db->quote($promotionCode);
            
            $where = "CouponCode = $coupon";
            
            $existsCoupon = $objCoupon->fetchRow($where);
            
            if (count($existsCoupon) > 0) {
                $now = date('Y-m-d', time());
                if (($existsCoupon->ExpiresDate == null) || $existsCoupon->ExpiresDate >= $now) {
                
                    $oneTimeOrAllTime = $existsCoupon->UseTime;
                    
                    $shopOrder = new ShopOrder();
            
                    if ($oneTimeOrAllTime == 'One') {
                        $user = $defaultNamespace->user;
                        
                        if ($user) {
                            $user_id = $defaultNamespace->CustomerNo;
                            $used = $shopOrder->fetchRow("coupon_code = $coupon AND user_id = '$user_id' AND order_status = 1");
                            
                            if (count($used)>0) {
                                 echo Zend_Json::encode(array("msg" => "You've used this promotion code!", "success" => false));
                                 die;
                            }
                        } else {
                            echo Zend_Json::encode(array("msg" => "Please login to use this promotion code!", "success" => false));
                            die;
                        }
                    }
                    
                    if ($defaultNamespace->cartTotal >= $existsCoupon->MinValue) {
                        $defaultNamespace->coupon = $couponSession = array(
                                            'CouponCode' => $existsCoupon->CouponCode,
                                            'CouponTitle' => $existsCoupon->CouponTitle,
                                            'CouponType' => $existsCoupon->CouponType,
                                            'MinValue' => $existsCoupon->MinValue,
                                            'Value' => $existsCoupon->Value,
                                            'CatID' => $existsCoupon->CatID,
                                        );
                        if ($existsCoupon->CouponType != 'FREEGIFT') {
                            // update coupon
                            $defaultNamespace = new Zend_Session_Namespace('Default');
                            $order_id = $defaultNamespace->orderID;
                            
                            if ($order_id > 0) {
                                $data = array('coupon_code' => $existsCoupon->CouponCode, 'CouponTitle' => $existsCoupon->CouponTitle);
                                $shopOrder->update($data , "order_id = '$order_id'");
                            }
                            
                            echo Zend_Json::encode(array("msg" => "Update successfull!", "success" => true, 'CouponCode' => $existsCoupon->CouponCode, 'CouponType' => $existsCoupon->CouponType,'Value' => $existsCoupon->Value));die;
                        } else {
                            // FREEGIFT
                            // SUM all product in cart has FreeGiftYN = Yes
                            $defaultNamespace = new Zend_Session_Namespace('Default');
                            $order_id = $defaultNamespace->orderID;
                            
                            if ($order_id > 0) {
                                $order_item = new ShopOrderItem();
                                
                                $where = "OrderID = '$order_id' AND FreeGiftYN = 'Yes'";
                                $sum = $order_item->getSum($where);
                                
                                //echo "/*$sum*/";
                                if ($sum < $existsCoupon->MinValue) {
                                    echo Zend_Json::encode(array("msg" => "To use this FREEGIFT, your cart must be at least: $" . $existsCoupon->MinValue, "success" => false));
                                    die;
                                } else {
                                    echo Zend_Json::encode(array("msg" => "Update successfull!", "success" => true));
                                    die;
                                }
                            }
                        }
                    } else {
                        echo Zend_Json::encode(array("msg" => "To use this promotion code, your cart must be at least: $" . $existsCoupon->MinValue, "success" => false));
                        die;
                    }
                } else {
                    echo Zend_Json::encode(array("msg" => "Promotion Code Has Expires!", "success" => false));die;
                }
            } else {
                echo Zend_Json::encode(array("msg" => "Wrong Promotion Code!", "success" => false));die;
            }
            die;
        }
        echo Zend_Json::encode(array("msg" => "Please insert Promotion Code!", "success" => false));
        die;
    }
    
    public function giftcardcheckoutAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function giftcardcheckoutinnerAction() {
    }
    
    public function giftcardprocesspaymentAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function giftcardprocesspaymentinnerAction() {
        $this->view->translate = new Zend_Translate('tmx', BASE_DIR . '/translate/admin.tmx', 'en');
        $this->processLoginAction();
        $defaultNamespace = new Zend_Session_Namespace('Default');
        
        $gcno = $this->getParam('gcno');
        
        if ($defaultNamespace->access) {
            $user = $defaultNamespace->user;
            $user_id = $user->CustomerNo;
            
            $shopOrder = new ShopOrder();
            
            $yourCart = $this->getCart();
            
            /*
            $description = array(
                'cart' => $yourCart,
                'shipInfo' => $defaultNamespace->shipInfo,
                'billInfo' => $defaultNamespace->billInfo,
                'total' => $defaultNamespace->cartTotal,
            );
            $data = array(
                'user_id' => $user_id,
                'description' => Zend_Json::encode($description),
                'date_created' => date('Y-m-d H:i:s', time()),
                'order_status' => 0,
            );
            */
            
            //$shopOrder->insert($data);
            
            $defaultNamespace = new Zend_Session_Namespace('Default');
            $order_id = $defaultNamespace->orderID;
            
            $where = "order_id = '$order_id'";
            
            $shopOrder->update(array('order_status' => 1), $where);
            
            
            $strMailBody = $defaultNamespace->mailBody;
                        
            $conf = Vnf::getConfigs('conf');
            
            $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
            @$emailshop = $conf->emailshop?$conf->emailshop:'info@'.$domain;
            
            // this code will use in next step
            if ($_SERVER['HTTP_HOST'] != 'localhost') {
                $mail = new Zend_Mail("utf-8");
                $mail->setBodyHtml($strMailBody)
                    ->setFrom($emailshop)
                    ->addTo($emailshop)
                    ->addBcc('ptp285@gmail.com')
                    ->addCc($user['Email'])
                    ->setSubject($this->view->translate->_('Order Information'))
                    ->send();
            }
            
            $giftcard = new Giftcard();
            
            $where = "GiftCardNo = '$gcno' AND ActiveYN=1";
            $card = $giftcard->fetchRow($where);
            
            if ($card) {
                
                $cardAmount = $card->Amount;
                $defaultNamespace->cartTotal;
                $maxAmount = $cardAmount>=$defaultNamespace->cartTotal?$defaultNamespace->cartTotal:$cardAmount;
                
                $giftcard->increaseValue("Amount", -1*$maxAmount , "BuyerID", $user_id , $where);
                
                if ($cardAmount >= $defaultNamespace->cartTotal) {
                    $this->view->message = "Thanks for your order. An email has been sent to your email. We will contact you soon!<br>Your card still remain $" . ($cardAmount - $maxAmount);
                    $defaultNamespace = new Zend_Session_Namespace('Default');
                    $partnerID = $defaultNamespace->reff;
                    if ($partnerID > 0) {
                        
                        $objPartner = new Partners();
                        
                        $objPartner->increaseValue("Ordered", 1, "PartnerID = '$partnerID'");
                    }
                    
                    $defaultNamespace->cartTotal = 0;
                    $defaultNamespace->coupon = null;
                    $defaultNamespace->methodPayment = null;
                    Zend_Session::regenerateId();
                    $this->view->useanother = false;
                } else {
                    $defaultNamespace->cartTotal -= $maxAmount;
                    $this->view->useanother = true;
                    $this->view->message = "Your card not enought to pay. We charged you $" . $maxAmount . ". Please use another method to pay $" .$defaultNamespace->cartTotal;
                }
                
            } else {
                $this->view->message = "Invalid gift card. Please try again with another gift card!";
                $this->view->useanother = true;
            }
            //$this->emptyCart();
            /*
            $defaultNamespace->cartSession = null;
            $defaultNamespace->shipInfo = null;
            $defaultNamespace->billInfo = null;
            $defaultNamespace->cartTotal = null;
            */
                    
       }
   }
   
    public function updatgiftcardAction() {

        $defaultNamespace = new Zend_Session_Namespace('Default');
        $gcno = $this->getParam('gcno', '');
        
        if ($gcno != '') {
            $giftcard = new Giftcard();
            
            $where = "GiftCardNo = '$gcno' AND ActiveYN=1";
            $card = $giftcard->fetchRow($where);
            
            if ($card) {
                if ($card->Amount > 0) {
                    $cardAmount = $card->Amount;
                    $defaultNamespace->cartTotal;
                    $maxAmount = $cardAmount>=$defaultNamespace->cartTotal?$defaultNamespace->cartTotal:$cardAmount;
                    
                    //$defaultNamespace->cartTotal -= $maxAmount;
                    
                    //$defaultNamespace->coupon = null;
                    $defaultNamespace->giftCard = $gcno;
                    $defaultNamespace->giftCardPrice = $maxAmount;
                    
                    echo Zend_Json::encode(array("msg" => "Gift card has been updated.", "success" => true, 'giftcardupdate' => $maxAmount, 'cartTotal' => $defaultNamespace->cartTotal - $maxAmount));die;
                } else {
                    echo Zend_Json::encode(array("msg" => "Your gift card is empty", "success" => false));
                    die;
                }
            } else {
                //echo Zend_Json::encode(array("msg" => "Gift card has been updated.", "success" => true, 'giftcardupdate' => $maxAmount, 'cartTotal' => $defaultNamespace->cartTotal - $maxAmount));die;
            }
        }
        echo Zend_Json::encode(array("msg" => "Can not use your gift card.", "success" => false));
        die;
    }
    
    public function paypalcheckoutAction() {
        $this->setLayout(DEFAULT_LAYOUT);
        $this->prepareData();
    }
    
    public function paypalcheckoutinnerAction() {
        
    }
    
    public function removegiftcartAction() {
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $defaultNamespace->giftCard = null;
        $defaultNamespace->giftCardPrice = null;
        $this->_redirect("shop/viewcart");
    }
    
    public function removecouponAction() {
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $defaultNamespace->coupon = null;
        $this->_redirect("shop/viewcart");
    }
    
    public function checksignatureAction() {
        
        $value = $this->getParam('v', 0);
        
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $defaultNamespace->SignatureConfirmation = $value;
        
        $this->_redirect("shop/viewcart");
    }
    
    public function shippingAction() {
        $value = $this->getParam('v', 0);
        
        $shippingType = array(
            '0' => 'Standard (5-7 Days): $0.00',
            '5.95' => 'Priority Shipping (2-3 Days): $5.95'
        );
        
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $defaultNamespace->shipping = $value;
        $defaultNamespace->shippingType = $shippingType['' . $value];
        
        
        $this->_redirect("shop/checkoutprocess");
    }
    public function checkpromotioncode() {
        
        $defaultNamespace = new Zend_Session_Namespace('Default');
        $existsCoupon = $defaultNamespace->coupon;
        
        if($existsCoupon) {
            $now = date('Y-m-d', time());
            
            $shopOrder = new ShopOrder();

            echo $defaultNamespace->cartTotal;
            $defaultNamespace = new Zend_Session_Namespace('Default');
            $order_id = $defaultNamespace->orderID;
            
            if ($defaultNamespace->cartTotal >= $existsCoupon['MinValue']) {
                // update them
                $couponSession = array(
                                    'CouponCode' => $existsCoupon['CouponCode'],
                                    'CouponTitle' => $existsCoupon['CouponTitle'],
                                    'CouponType' => $existsCoupon['CouponType'],
                                    'Value' => $existsCoupon['Value'],
                                    'CatID' => $existsCoupon['CatID'],
                                );
                if ($existsCoupon['CouponType'] != 'FREEGIFT') {
                    // update coupon
                    // check xem $ hay % co thoa man dieu kien ko
                        $order_item = new ShopOrderItem();
                        
                        $where = "OrderID = '$order_id'";
                        
                        
                        
                } else {
                    // FREEGIFT
                    // SUM all product in cart has FreeGiftYN = Yes
                    
                    if ($order_id > 0) {
                        $order_item = new ShopOrderItem();
                        
                        $where = "OrderID = '$order_id' AND FreeGiftYN = 'Yes'";
                        $sum = $order_item->getSum($where);
                        
                        //echo "/*$sum*/";
                        if ($sum < $existsCoupon['MinValue']) {
                            $defaultNamespace->coupon = null;
                            $this->view->errormessage = "Your cart total may be at least: \$" . $existsCoupon['MinValue'];
                        }
                    }
                }
            } else {
               $defaultNamespace->coupon = null;
            }
        }
        
    }
}
?>